package com.example.lncd.ui.auth;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.lncd.R;
import com.example.lncd.api.ApiService;
import com.example.lncd.api.RetrofitClient;
import com.example.lncd.model.User;
import com.example.lncd.util.PreferenceManager;
import com.google.android.material.textfield.TextInputEditText;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginFragment extends Fragment {

    private TextInputEditText etUsername, etPassword;
    private Button btnLogin;
    private ApiService apiService;
    private PreferenceManager preferenceManager;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        
        // 初始化视图
        etUsername = view.findViewById(R.id.etUsername);
        etPassword = view.findViewById(R.id.etPassword);
        btnLogin = view.findViewById(R.id.btnLogin);
        
        // 初始化API服务和偏好管理器
        apiService = RetrofitClient.getApiService();
        preferenceManager = new PreferenceManager(requireContext());
        
        // 设置登录按钮点击事件
        btnLogin.setOnClickListener(v -> loginUser());
        
        return view;
    }
    
    private void loginUser() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        
        // 验证输入
        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(requireContext(), "请填写所有字段", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 创建登录请求对象
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);
        
        // 调用登录API
        Call<User> call = apiService.loginUser(loginUser);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful() && response.body() != null) {
                    User user = response.body();
                    Log.d("LoginFragment", "登录成功，用户ID: " + user.getId());
                    
                    // 保存用户信息到本地
                    preferenceManager.saveUser(user);
                    
                    // 检查userType是否为空
                    if (user.getUserType() == null) {
                        // 用户类型为空，跳转到角色选择页面
                        Toast.makeText(requireContext(), "请选择您的角色", Toast.LENGTH_SHORT).show();
                        ((LoginActivity) requireActivity()).navigateToRoleSelection(user.getId());
                        return;
                    }
                    
                    // 根据用户类型跳转到不同页面
                    if (user.getUserType() == User.UserType.ELDERLY) {
                        ((LoginActivity) requireActivity()).navigateToElderlyMain();
                    } else if (user.getUserType() == User.UserType.FAMILY) {
                        ((LoginActivity) requireActivity()).navigateToFamilyMain();
                    } else {
                        ((LoginActivity) requireActivity()).navigateToRoleSelection(user.getId());
                    }
                } else {
                    Toast.makeText(requireContext(), "登录失败：用户名或密码错误", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Toast.makeText(requireContext(), "网络错误：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
} 